package com.runa.monitor.platinterface.netservice.equipment;

import com.alibaba.fastjson.JSON;
import com.hdb.api.adv.HdbData;
import com.runa.monitor.comm.dto.Archive;
import com.runa.monitor.comm.dto.Node;
import com.runa.monitor.comm.dto.newComm.HotMeterVO;
import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.monitor.platinterface.backwork.util.FileUtils;
import com.runa.monitor.platinterface.extend.hdb.GatewayHdbClient;
import com.runa.monitor.platinterface.extend.hdb.HdbProperty;
import com.runa.monitor.platinterface.extend.hdb.HdbResponse;
import com.runa.monitor.platinterface.backwork.function.TaskFunction;
import com.runa.monitor.platinterface.netservice.connect.commstatus.CommStatus;
import com.runa.rccprotocol.dto.equdata.EquData;
import com.runa.rccprotocol.dto.param.ExtendParam;
import com.runa.rccprotocol.dto.runa.RunaConcenAffirmDeny;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Slf4j
public class HDBDriver extends NetEqu<String> {

    public HDBDriver(String serial) {
        super(serial, null);
    }

    @SneakyThrows
    public static void main(String[] args) {
        String s = "M_Xsyy_1_1Unit\t西山御园1号楼\t门头沟小区;西山御园\t\t西山御园1号楼\t300000\t1000\t1800000\t\t1061\n" +
                "M_Xsyy_2_1Unit\t西山御园2号楼\t门头沟小区;西山御园\t\t西山御园2号楼\t300000\t1000\t1800000\t\t1062\n" +
                "M_Xsyy_3_1Unit\t西山御园3号楼\t门头沟小区;西山御园\t\t西山御园3号楼\t300000\t1000\t1800000\t\t1063\n" +
                "M_Xsyy_4_1Unit\t西山御园4号楼\t门头沟小区;西山御园\t\t西山御园4号楼\t300000\t1000\t1800000\t\t1064\n" +
                "M_Xsyy_5_1Unit\t西山御园5号楼\t门头沟小区;西山御园\t\t西山御园5号楼\t300000\t1000\t1800000\t\t1065\n" +
                "M_Xsyy_6_1Unit\t西山御园6号楼\t门头沟小区;西山御园\t\t西山御园6号楼\t300000\t1000\t1800000\t\t1066\n" +
                "M_Xsyy_7_1Unit\t西山御园7号楼\t门头沟小区;西山御园\t\t西山御园7号楼\t300000\t1000\t1800000\t\t1067\n" +
                "M_Xsyy_8_1Unit\t西山御园8号楼\t门头沟小区;西山御园\t\t西山御园8号楼\t300000\t1000\t1800000\t\t1068\n" +
                "M_Xsyy_9_1Unit\t西山御园9号楼\t门头沟小区;西山御园\t\t西山御园9号楼\t300000\t1000\t1800000\t\t1069\n" +
                "M_Xsyy_11_1Unit\t西山御园11号楼\t门头沟小区;西山御园\t\t西山御园11号楼\t300000\t1000\t1800000\t\t1070\n" +
                "M_Xsyy_12_1Unit\t西山御园12号楼\t门头沟小区;西山御园\t\t西山御园12号楼\t300000\t1000\t1800000\t\t1071\n" +
                "M_Xsyy_13_1Unit\t西山御园13号楼\t门头沟小区;西山御园\t\t西山御园13号楼\t300000\t1000\t1800000\t\t1072\n" +
                "M_Xsyy_14_1Unit\t西山御园14号楼\t门头沟小区;西山御园\t\t西山御园14号楼\t300000\t1000\t1800000\t\t1073\n" +
                "M_Xsyy_15_1Unit\t西山御园15号楼\t门头沟小区;西山御园\t\t西山御园15号楼\t300000\t1000\t1800000\t\t1074\n" +
                "M_Xsyy_16_1Unit\t西山御园16号楼\t门头沟小区;西山御园\t\t西山御园16号楼\t300000\t1000\t1800000\t\t1075";
        Integer[] ss = {23000340, 23000341, 23000345, 23000298, 23000343, 23000344
                , 23000346, 23000352, 23000297, 23000351, 23000350, 23000339, 23000337, 23000335, 23000296};
        StringBuilder z = new StringBuilder();
        String[] spl = s.split("\\n");
        for (int i = 0; i < spl.length; i++) {
            String s2 = spl[i].split("\\t")[0];
            z.append("网络设备编号：").append(ss[i]).append("：表编号：11：采集器名：").append(s2).append("：低区\n");
            z.append("网络设备编号：").append(ss[i]).append("：表编号：21：采集器名：").append(s2).append("：高区\n");
            z.append("网络设备编号：").append(ss[i]).append("：阀编号：12：采集器名：").append(s2).append("：低区\n");
            z.append("网络设备编号：").append(ss[i]).append("：阀编号：22：采集器名：").append(s2).append("：高区\n");
        }
        System.out.println(z);
    }

    /**
     * [{"alarmType":"NONE","quality":"GOOD","timestamp":1699513234059,"type":"R4","value":-87.12000274658203},{"alarmType":"NONE","quality":"GOOD","timestamp":1699513234059,"type":"R4","value":37.880001068115234},{"alarmType":"NONE","quality":"GOOD","timestamp":1699513234059,"type":"R4","value":0.0}]
     */
    @SneakyThrows
    @Override
    public void readNodeEqu(List<Node> nodes, TaskFunction function, EquData.EquDataType type) {
        try {
            log.info("HDBDriver readNodeEqu start" + JSON.toJSONString(nodes));
//        HouseEquIDataService dataService = SpringUtil.getBean(HouseEquIDataService.class);
//        List<String> list = nodes.stream().map(Node::getSerial).collect(Collectors.toList());
            String s = null;
            for (Node node : nodes) {
                BufferedReader bufferedReader = FileUtils.getBufferedReader("/runa/hdb.txt");//
                if (bufferedReader == null) {
                    log.error("目录下无此文件hdb.txt！！！！！！");
                    return;
                }
                if (type == EquData.EquDataType.PUBLIC_UNIT) {
                    s = "网络设备编号：" + serial() + "：阀编号：" + node.getSerial();
                } else {
                    s = "网络设备编号：" + serial() + "：表编号：" + node.getSerial();
                }
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.startsWith(s)) {
                        log.info("找到对应hdb数据：" + line);
                        String[] split = line.split("：");
                        String jiName = split[5];
                        String qu = split[6];
                        if (type == EquData.EquDataType.PUBLIC_UNIT) {
                            String[] tags = new String[4];//写入点位
                            if (qu.equalsIgnoreCase("高区")) {
                                tags[0] = jiName + ".H_ValveFeed_Set";
                                tags[1] = jiName + ".H_ValveFeed_Back";
                                tags[2] = jiName + ".H_GoTemp";
                                tags[3] = jiName + ".H_BackTemp";
                            } else {
                                tags[0] = jiName + ".L_ValveFeed_Set";
                                tags[1] = jiName + ".L_ValveFeed_Back";
                                tags[2] = jiName + ".L_GoTemp";
                                tags[3] = jiName + ".L_BackTemp";
                            }
                            HdbResponse hdbResponse = GatewayHdbClient.getInstance().readCurrentByName(tags);
                            if (!hdbResponse.isSuccess()) {
                                log.error("HDBDriver readNodeEqu ERROR---" + JSON.toJSONString(nodes));
                            }
                            List<HdbData> dataList = hdbResponse.getHdbDataList();

                            ValveVO valveVO = new ValveVO();
                            try {
                                valveVO.setValveSerial(node.getSerial());
                                valveVO.setActOpen(((Double) dataList.get(1).value).floatValue());
                                valveVO.setReadTime(dataList.get(0).timestamp);
                                valveVO.setRemoteSet(((Double) dataList.get(0).value).floatValue());
                                valveVO.setSupplyTemp(((Double) dataList.get(2).value).floatValue());
                                valveVO.setReturnTemp(((Double) dataList.get(3).value).floatValue());
                            } catch (Exception e) {
                                log.error("valveVO.set异常------",e);
                                valveVO.setSuccess(false);
                            }
                            function.setStatus(Collections.singletonList(node));
                            function.doApply(CommStatus.OK, Collections.singletonList(valveVO));
                        } else {
                            String[] tags = new String[6];//写入点位
                            if (qu.equalsIgnoreCase("高区")) {
                                tags[0] = jiName + ".H_GoTemp";
                                tags[1] = jiName + ".H_BackTemp";
                                tags[2] = jiName + ".H_Flow";
                                tags[3] = jiName + ".H_Hot";
                                tags[4] = jiName + ".H_TotalFlow";
                                tags[5] = jiName + ".H_TotalHot";
                            } else {
                                tags[0] = jiName + ".L_GoTemp";
                                tags[1] = jiName + ".L_BackTemp";
                                tags[2] = jiName + ".L_Flow";
                                tags[3] = jiName + ".L_Hot";
                                tags[4] = jiName + ".L_TotalFlow";
                                tags[5] = jiName + ".L_TotalHot";
                            }
                            HdbResponse hdbResponse = GatewayHdbClient.getInstance().readCurrentByName(tags);
                            if (!hdbResponse.isSuccess()) {
                                log.error("HDBDriver readNodeEqu ERROR---" + JSON.toJSONString(nodes));
                            }
                            List<HdbData> dataList = hdbResponse.getHdbDataList();

                            HotMeterVO hotMeterVO = new HotMeterVO();
                            hotMeterVO.setMeterSerial(node.getSerial());
                            try {
                                hotMeterVO.setSupplyTemp(((Double) dataList.get(0).value).floatValue());
                                hotMeterVO.setReturnTemp(((Double) dataList.get(1).value).floatValue());
                                hotMeterVO.setFlow(((Double) dataList.get(2).value).floatValue());
                                hotMeterVO.setPower(((Double) dataList.get(3).value).floatValue());
                                hotMeterVO.setAccFlow(((Double) dataList.get(4).value).floatValue());
                                hotMeterVO.setAccHeat(((Double) dataList.get(5).value).floatValue());
                                hotMeterVO.setReadDate(dataList.get(0).timestamp);
                            } catch (Exception e) {
                                log.error("hotMeterVO.set异常------",e);
                                hotMeterVO.setSuccess(false);
                            }
                            function.setStatus(Collections.singletonList(node));
                            function.doApply(CommStatus.OK, Collections.singletonList(hotMeterVO));
                        }
                        break;
                    }
                    if (line.equalsIgnoreCase("END")) {
                        log.error("当前设备hdb文件未找到数据:" + JSON.toJSONString(node));
                    }
                }
                bufferedReader.close();
            }


//        while ((line = bufferedReader.readLine()) != null) {
//            if (line.equalsIgnoreCase("编号")) {
//
//            }
//
//            if (line.startsWith("编号")) {
//                String[] split = line.split("：");
//                if (list.contains(split[1])) {//匹配到下发
//
//
//                }
//            }
////            log.info(line);
//        }
//        bufferedReader.close();
        } catch (Exception e) {
            log.error("获取HDB数据异常",e);
            
        } finally {
        }


    }

    @Override
    public void setNodeEquArchive(List<Archive> archives, TaskFunction function) {

    }

//    public static void main(String[] args) {
//        String s = hexFormat("68590059006841023701000004FF00000201112233440100000000000000001234567140420287111100213612557704004821312D312D310000000000000000000000000000000000000000000000000000008CC32800F49428008CC328009316");
//        System.out.println(s);
//    }

    private String hexFormat(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < s.length(); i += 2) {
            stringBuilder.append(s.substring(i, i + 2)).append(" ");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
    }

    @Override
    public void clearNodeEquArchive(TaskFunction function) {

    }


    @Override
    public void valveOnOffControl(List<Node> nodeList, boolean ifLock, Integer opening, TaskFunction function) {

    }

    @Override
    public void readNodeRecord(List<Integer> indexes, TaskFunction function) {

    }

    @SneakyThrows
    @Override
    public void sentPublicUnitRecord(List<Node> nodeList, Integer model, Map param, TaskFunction function) {
        log.info("HDBDriver valveOnOffControl start" + JSON.toJSONString(nodeList));
        for (Node node : nodeList) {
            BufferedReader bufferedReader = FileUtils.getBufferedReader("/runa/hdb.txt");//
            if (bufferedReader == null) {
                log.error("目录下无此文件hdb.txt！！！！！！");
                return;
            }
            String s = "网络设备编号：" + serial() + "：阀编号：" + node.getSerial();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.startsWith(s)) {
                    log.info("找到对应hdb数据：" + line);
                    String[] split = line.split("：");
                    String jiName = split[5];
                    String qu = split[6];
                    String[] tags = new String[1];//写入点位
                    String[] values = new String[1];
                    values[0] = param.get("targetValue").toString();
                    if (qu.equalsIgnoreCase("高区")) {
//                        tags[0] = jiName + ".H_AIValveFeed_Set";
                        tags[0] = jiName + ".H_ValveFeed_Set";
                    } else {
//                        tags[0] = jiName + ".L_AIValveFeed_Set";
                        tags[0] = jiName + ".L_ValveFeed_Set";
                    }
                    HdbResponse hdbResponse = GatewayHdbClient.getInstance().WriteBatchTagValues(HdbProperty.getUser(), tags, values);
                    if (!hdbResponse.isSuccess()) {
                        log.error("HDBDriver valveOnOffControl ERROR---" + JSON.toJSONString(nodeList));
                    }
//                    List<HdbData> dataList = hdbResponse.getHdbDataList();
                    log.info("HDBDriver valveOnOffControl 完成，发送消息");
                    function.setStatus(node);
                    function.doApply(CommStatus.OK, new RunaConcenAffirmDeny(true));
                    break;
                }
                if (line.equalsIgnoreCase("END")) {
                    log.error("当前设备hdb文件未找到数据:" + JSON.toJSONString(node));
                }
            }
            bufferedReader.close();
        }
//        TaskManager taskQueue = SpringUtil.getBean(TaskManager.class);
//        CtrlValveTask task = new CtrlValveTask();
//        task.setNetEquNo(serial());
//        task.setEquNo(nodeList.stream().map(node -> {
//            function.setStatus(node.getId());
//            return node.getSerial();
//        }).collect(Collectors.toList()));
//        task.setOpening(opening);
//        task.setIfLock(ifLock);
//        taskQueue.offer(serial(), task);
    }

    @Override
    public void sentPublicUnitModel(List<Node> nodeList, boolean model, TaskFunction function) {

    }

    @Override
    public void sentExtendParam(ExtendParam param, TaskFunction function) {

    }

    @Override
    public void readPublicUnitRecord(Node valve, Integer model, TaskFunction function) {

    }

    @Override
    public void readPublicUnitAndMeter(Node valve, Node meter, TaskFunction function) {

    }

    @Override
    public void heartbeatUpdate() {

    }

    @Override
    public boolean heartStop() {
        return false;
    }
}
